package com.tony.mindwarning.controller;

import com.alibaba.fastjson.JSONObject;
import com.tony.mindwarning.pojo.Log;
import com.tony.mindwarning.pojo.Type;
import com.tony.mindwarning.pojo.User;
import com.tony.mindwarning.service.LogService;
import com.tony.mindwarning.service.UserService;
import com.tony.mindwarning.utils.DateUtils;
import com.tony.mindwarning.utils.DbUtils;
import com.tony.mindwarning.utils.MessageResults;
import com.tony.mindwarning.utils.PageUtils;
import com.upyun.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static com.tony.mindwarning.utils.UpYunUtils.testSync;

/**
 * Created with IntelliJ IDEA.
 *
 * @Title: UserController
 * @Auther: 皮蛋布丁
 * @Date: 2021/04/06/22:39
 * @Description:
 */
@Controller
@Scope("prototype")
public class UserController {

    @Resource
    UserService userService;
    @Resource
    LogService logService;

    /**
     * 01-ajax登录
     * @param user
     * @return
     */
    @PostMapping("/user_login")
    @ResponseBody
    public MessageResults login(User user, String ucode, String ip, String city, HttpSession session){
        System.out.println("登录ip是:"+ip);
        System.out.println("登录地址是:"+city);
        MessageResults reqults=null;
        //系统生成的验证码
        String checkcode=(String) session.getAttribute("checkcode");
        //校验系统生成的验证码
        if(checkcode.equalsIgnoreCase(ucode)){
            User userLogin = userService.userLogin(user);
            if(userLogin!=null){
                //用户的登录信息
                session.setAttribute("userLogin",userLogin);
                Log log=new Log(userLogin.getUname(), DateUtils.getNowTime(),ip,city);
                logService.addLog(log);

                reqults=new MessageResults(200,"登录成功",userLogin);
            }else{
                reqults=new MessageResults(500,"登录失败",null);
            }
        }else{
            reqults=new MessageResults(501,"验证码输入错误!",null);
        }
        return reqults;
    }

    /**
    * @Description: logout 用户退出
    * @Param: [session]
    * @return: java.lang.String
    * @Author: 皮蛋布丁
    */
    @RequestMapping("/user_logout")
    public String logout(HttpSession session){
        User user= (User)session.getAttribute("userLogin");
        //备份数据库
        ///backup/mind_waring_mysql
        if (DbUtils.backup("139.224.195.30",
                "root",
                "z1597924",
                "/backup/mind_waring_mysql/",
                user.getUname()+"操作-"+DateUtils.getTime(),
                "mindwarning")) {
            System.out.println("数据库备份成功!");
        } else {
            System.out.println("数据库备份失败!");
        }
        //恢复数据库
        if (DbUtils.recover("/backup/mind_waring_mysql/Tony操作-2021-06-08-13-43-17.sql",
                            "139.224.195.30",
                            "mindwarning",
                            "root",
                            "z1597924")) {

        } else {

        }

        session.invalidate();


        return "redirect:/login";
    }

    /**
    * @Description: getLogs 查询用户的登录日志信息
    * @Param: [session]
    * @return: com.tony.mindwarning.utils.MessageReqults
    * @Author: 皮蛋布丁
    */
    @ResponseBody
    @RequestMapping("/user_getLogs")
    public MessageResults getLogs(HttpSession session){
        MessageResults reqults=null;
        User user= (User)session.getAttribute("userLogin");
        List<Log> logs = logService.getLogs(user.getUname());
        reqults=new MessageResults(200,"登录日志",logs);
        return reqults;
    }

    /**
    * @Description: queryPage 用户列表(分页)
    * @Param: [pageIndex, pageSize, model]
    * @return: java.lang.String
    * @Author: 皮蛋布丁
    */
    @RequestMapping("/user_page")
    public String queryPage(@RequestParam(value = "pageIndex",defaultValue = "1") Integer pageIndex,
                            @RequestParam(value = "pageSize",defaultValue = "5") Integer pageSize, Model model) {

        //总条数
        Integer totalCount = userService.getTotlCount();
        Map<String, Object> map = new HashMap<String, Object>();
        //开始查询的位置
        map.put("startIndex",(pageIndex-1)*pageSize);
        map.put("pageSize",pageSize);
        //每页的数据
        List<User> users = userService.getUserByPage(map);
        //封装数据
        PageUtils<User> pageUtils = new PageUtils<>(pageIndex,pageSize,totalCount,users);
        System.out.println("分页工具类：" + pageUtils);
        model.addAttribute("pageUtils",pageUtils);
        System.out.println(pageUtils);
        return "user";
    }

    /**
    * @Description: updateUserTypeById 用户账号启用/禁用
    * @Param: [id, ustate]
    * @return: com.tony.mindwarning.utils.MessageResults
    * @Author: 皮蛋布丁
    */
    @ResponseBody
    @RequestMapping("/user_state")
    public MessageResults updateUserTypeById(HttpSession session,int id,String ustate){
        String state = (ustate.equalsIgnoreCase("0"))?"1":"0";
        String state_name = (ustate.equalsIgnoreCase("0"))?"禁用":"启用";
        User user= (User)session.getAttribute("userLogin");
        Integer count = userService.updateUserTypeById(id,state,user.getId());
        MessageResults results=null;
        if(count>0){
            results=new MessageResults(200,state_name + "成功！",null);
        }else{
            results=new MessageResults(500,state_name + "失败！",null);
        }
        return results;
    }

    /**
    * @Description: delUserById 根据id删除用户账号
    * @Param: [id]
    * @return: com.tony.mindwarning.utils.MessageResults
    * @Author: 皮蛋布丁
    */
    @ResponseBody
    @RequestMapping("/user_delete")
    public MessageResults delUserById(HttpSession session,int id){
        User user= (User)session.getAttribute("userLogin");
        Integer count = userService.delUserById(id,user.getId());
        MessageResults results=null;
        if(count>0){
            results=new MessageResults(200,"删除成功！",null);
        }else{
            results=new MessageResults(500,"删除失败！",null);
        }
        return results;
    }

    /**
    * @Description: findUserById 根据id获取用户详情
    * @Param: [id, model]
    * @return: java.lang.String
    * @Author: 皮蛋布丁
    */
    @RequestMapping("/user_getById")
    public String findUserById(Integer id, Model model){
        User user = userService.findUserById(id);
        model.addAttribute("user",user);
        System.out.println("要更新的对象是:"+user);
        return "userDetails";
    }

    /**
    * @Description: editUserById 跳转编辑页面
    * @Param: [id, model]
    * @return: java.lang.String
    * @Author: 皮蛋布丁
    */
    @RequestMapping("/user_editUserById")
    public String editUserById(Integer id, Model model){
        User user = userService.findUserById(id);
        model.addAttribute("user",user);
        System.out.println("要更新的对象是:"+user);
        return "userEdit";
    }

    /**
    * @Description: updateProduct 编辑更新用户
    * @Param: [user, file, response, request]
    * @return: void
    * @Author: 皮蛋布丁
    */
    @RequestMapping("/user_update")
    public void updateProduct(HttpSession session,User user, @RequestParam("file") MultipartFile file, HttpServletResponse response, HttpServletRequest request)throws Exception{
        response.setContentType("text/html;charset=utf-8");
        User currUser= (User)session.getAttribute("userLogin");
        user.setUpdate_user_id(currUser.getId());
        System.out.println("要更新的用户是:"+user);
        if(file.isEmpty()==false){
            //上传的文件不为空
            String filename = file.getOriginalFilename();
            //获取文件的后缀
            String suffixName = filename.substring(filename.lastIndexOf("."));
            //生成一个新的文件名
            filename= UUID.randomUUID()+suffixName;
            System.out.println("要上传服务器的文件名是:"+filename);

            //上传又拍云
            byte [] byteArr=file.getBytes();
            Result upyunData = testSync(byteArr,filename);
            JSONObject photoMsg = JSONObject.parseObject(upyunData.getMsg());
            String photeUrl = "http://mind-warning.test.upcdn.net" + photoMsg.getString("url");

//            //获取文件上传的路径
//            File path=new File(ResourceUtils.getURL("classpath:").getPath());
//            File upload=new File(path.getAbsolutePath(),"/public/upload/"+filename);
//            file.transferTo(upload);
//            System.out.println("文件上传成功:"+upload.getAbsolutePath());
//            user.setUimage(filename);

            System.out.println("文件上传成功，地址为："+photeUrl);
            user.setUimage(photeUrl);
        }

        int count = userService.updateUserById(user);
        if(count>0){
            response.getWriter().write("<script>alert('更新成功!');location.href='user_page';</script>");
        }else{
            response.getWriter().write("<script>alert('更新失败!');location.href='user_getById?id='"+user.getId()+";</script>");
        }
    }

    /**
    * @Description: addProduct 新增用户
    * @Param: [user, file, response, request]
    * @return: void
    * @Author: 皮蛋布丁
    */
    @RequestMapping("/user_add")
    public void addProduct(HttpSession session,User user, @RequestParam("file") MultipartFile file, HttpServletResponse response, HttpServletRequest request)throws Exception{
        response.setContentType("text/html;charset=utf-8");
        User currUser= (User)session.getAttribute("userLogin");
        user.setCreate_user_id(currUser.getId());
        user.setUpdate_user_id(currUser.getId());
        //判断用户名是否重复
        Integer i = userService.compareUno(user.getUno());
        if (i != null) {
            response.getWriter().write("<script>alert('此用户名已存在，请重新填写！');location.href='user_page';</script>");
            return;
        }

        System.out.println("新增的用户是:"+user);
        if(file.isEmpty()){
            response.getWriter().write("<script>alert('上传的头像不能为空!');location.href='user_page';</script>");
            return;
        }
        //上传的文件不为空
        String filename = file.getOriginalFilename();
        //获取文件的后缀
        String suffixName = filename.substring(filename.lastIndexOf("."));
        //生成一个新的文件名
        filename= UUID.randomUUID()+suffixName;
        System.out.println("要上传服务器的文件名是:"+filename);

        //上传又拍云
        byte [] byteArr=file.getBytes();
        Result upyunData = testSync(byteArr,filename);
        JSONObject photoMsg = JSONObject.parseObject(upyunData.getMsg());
        String photeUrl = "http://mind-warning.test.upcdn.net" + photoMsg.getString("url");

//        //获取文件上传的路径
//        File path=new File(ResourceUtils.getURL("classpath:").getPath());
//        File upload=new File(path.getAbsolutePath(),"/public/upload/"+filename);
//        file.transferTo(upload);
//        System.out.println("文件上传成功:"+upload.getAbsolutePath());

        System.out.println("文件上传成功，地址为："+photeUrl);
        user.setUimage(photeUrl);
        int count = userService.addUser(user);
        if(count>0){
            response.getWriter().write("<script>alert('新增成功!');location.href='user_page';</script>");
        }else{
            response.getWriter().write("<script>alert('新增失败!');location.href='user_page';</script>");
        }
    }

    /**
    * @Description: updatePwdById 密码更新
    * @Param: [id, upass]
    * @return: com.tony.mindwarning.utils.MessageResults
    * @Author: 皮蛋布丁
    */
    @RequestMapping("/user_updatePwd")
    public void updatePwdById(HttpSession session, HttpServletResponse response,String oldPwd,String newPwd) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        User userLogin = (User) session.getAttribute("userLogin");
        User user = userService.findUserById(userLogin.getId());
        if (!user.getUpass().equalsIgnoreCase(oldPwd)) {
            response.getWriter().write("<script>alert('原密码不一致!');location.href='user_page';</script>");
            return;
        }
        if (user.getUpass().equalsIgnoreCase(newPwd)) {
            response.getWriter().write("<script>alert('新密码与原密码一致,请重新修改!');location.href='user_page';</script>");
            return;
        }
        Integer count = userService.updatePwdById(userLogin.getId(),newPwd);
        if(count>0){
            response.getWriter().write("<script>alert('密码更新成功!');location.href='user_page';</script>");
        }else{
            response.getWriter().write("<script>alert('密码更新失败!');location.href='user_page';</script>");
        }
    }

    /**
    * @Description: updatePwd 跳转密码修改页面
    * @Param: []
    * @return: java.lang.String
    * @Author: 皮蛋布丁
    */
    @RequestMapping("/updatePwd_page")
    public String updatePwd(){
        return "updatePwd";
    }


}
